const storageManager = require('../../../manager/storageManager').getInstance();

Component({
  properties: {},
  data: {
    importBookName: '',
    showHistoryLink: false
  },
  lifetimes: {
    attached() {
      // 初始化数据管理器 - 使用全局实例
      const app = getApp();
      this.wordDataManager = app.globalData.wordDataManager;
      // 检查是否有导入历史记录
      const history = storageManager.getStorage(storageManager.STORAGE_KEYS.IMPORT_HISTORY) || [];
      this.setData({ showHistoryLink: history.length > 0 });
    }
  },
  methods: {
    onRefresh() {
      // 刷新时检查是否有导入历史记录
      const history = storageManager.getStorage(storageManager.STORAGE_KEYS.IMPORT_HISTORY) || [];
      this.setData({ showHistoryLink: history.length > 0 });
    },
    onNameInput(e) {
      this.setData({ importBookName: e.detail.value });
    },
    chooseFile() {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['txt'],
        success: (res) => {
          const tempFilePath = res.tempFiles[0].path;
          const fileName = res.tempFiles[0].name.replace('.txt', '');
          const bookName = this.data.importBookName || fileName;
          this.importWordsFromTxt(tempFilePath, bookName);
        },
        fail: () => {
          wx.showToast({ title: '文件选择失败', icon: 'none' });
        }
      });
    },
    importWordsFromTxt(filePath, bookName) {
      wx.showLoading({ title: '导入中...' });
      this.wordDataManager.importBookFromTxt(filePath, bookName)
        .then(result => {
          this.addToImportHistory(bookName, result.wordCount);
          
          // 构建详细的导入结果信息
          let message = `导入成功，共${result.wordCount}个单词`;
          
          // 如果有关于总行数和跳过行数的信息，添加到提示中
          if (result.totalLines !== undefined) {
            message += `\n文件共${result.totalLines}行`;
          }
          
          if (result.skippedLines > 0) {
            message += `\n跳过${result.skippedLines}行`;
            
            // 在控制台打印跳过的详细信息，以便调试
            console.warn(`导入过程中跳过的行:`, result.skippedDetails);
            
            // 如果有跳过的行，显示更详细的提示
            wx.hideLoading();
            wx.showModal({
              title: '导入结果',
              content: message + '\n\n提示：部分行可能因格式不符合要求被跳过\n（要求每行至少包含单词和中文意思两个部分）',
              showCancel: false,
              success: () => {
                this.setData({
                  importBookName: '',
                  showHistoryLink: true
                });
                this.triggerEvent('importsuccess');
              }
            });
          } else {
            // 显示导入成功提示
            wx.hideLoading();
            wx.showToast({ title: message, icon: 'success' });
            
            // 开始同步单词详细信息
            this.syncWordDetails(result.bookId, result.wordCount);
            
            this.setData({
              importBookName: '',
              showHistoryLink: true // 导入成功后显示历史链接
            });
            // 导入成功后触发事件，通知父组件关闭弹窗并刷新列表
            console.log('导入成功，触发importsuccess事件');
            this.triggerEvent('importsuccess');
          }
        })
        .catch(error => {
          wx.hideLoading();
          wx.showToast({ title: '导入失败：' + error.message, icon: 'none' });
        });
    },
    
    /**
     * 同步单词详细信息
     * @param {string} bookId - 词书ID
     * @param {number} wordCount - 单词数量
     */
    syncWordDetails(bookId, wordCount) {
      // 如果单词数量为0，直接返回
      if (wordCount === 0) {
        return;
      }
      
      // 显示同步进度弹窗
      wx.showLoading({
        title: `正在获取单词详情... 0/${wordCount}`,
        mask: true
      });
      
      // 同步单词详情
      this.wordDataManager.syncBookWords(bookId, {
        onProgress: (progress) => {
          // 更新进度提示
          wx.showLoading({
            title: `正在获取单词详情... ${progress.processed}/${progress.total}`,
            mask: true
          });
        },
        onComplete: (result) => {
          wx.hideLoading();
          // 显示同步完成提示
          wx.showToast({
            title: '单词详情获取完成',
            icon: 'success',
            duration: 2000
          });
        },
        onError: (error) => {
          wx.hideLoading();
          // 显示同步失败提示
          wx.showToast({
            title: '单词详情获取失败: ' + error.message,
            icon: 'none',
            duration: 3000
          });
        }
      });
    },
    addToImportHistory(bookName, wordCount) {
      const history = storageManager.getStorage(storageManager.STORAGE_KEYS.IMPORT_HISTORY) || [];
      const newHistoryItem = {
        bookName,
        wordCount,
        time: this.formatDateTime(new Date())
      };
      const updated = [newHistoryItem, ...history].slice(0, 10);
      storageManager.setStorage(storageManager.STORAGE_KEYS.IMPORT_HISTORY, updated);
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    navigateToHistory() {
      wx.navigateTo({
        url: '/pages/vocabulary/import-history'
      });
    }
  }
});
